﻿using System;
using System.Data.SqlClient;
using System.Text;
using PropertyExpression.Common;

namespace PropertyExpression.ControllableQuery.Test2
{
    class Program
    {
        static void Main()
        {
            Foo(new DateTime(2000, 1, 1));
        }

        private static void Foo(DateTime? date)
        {
            using (var connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    var prototype = new {date, command}.Apply(p => {
                        var builder = new StringBuilder(@"
SELECT  TOP 1
        Id, CreationDate
FROM    Post
WHERE   1 = 1");
                        if (date.HasValue)
                        {
                            builder.Append(@"
        AND CreationDate >= @Date");
                            p.command.AddParameter("@Date", date);
                        }
                        p.command.CommandText = builder.ToString();
                        return default(T001);
                    });
                    using (var reader = command.ExecuteReader())
                        while (reader.Read())
                        {
                            var record = reader.Materialize(prototype);
                            Console.WriteLine("{0}, {1}", record.Id, record.CreationDate);
                        }
                }
            }
        }

        public static string ConnectionString
        {
            get { return @"Data Source=(local)\SQL2012;Initial Catalog=Serverfault;Integrated Security=True"; }
        }
    }
}
